package cn.itcast.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Component
@Aspect
public class AddCreateTimeUpdateTimeAspect {

    @Around("@annotation(AutoFill)")//注解方式
    //    @Around("execution(* cn.itcast.service.*.add(..)) || execution(* cn.itcast.service.*.update(..))")
    public Object AddCreatTimeAndUpdateTime(ProceedingJoinPoint pjp) throws Throwable {

        Object[] args = pjp.getArgs();

        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            Class<?> aClass = arg.getClass();
            Field createTime = aClass.getDeclaredField("createTime");
            Field updateTime = aClass.getDeclaredField("updateTime");
            if (createTime != null){
                createTime.setAccessible(true);
                createTime.set(arg, LocalDateTime.now());
            }
            if (updateTime != null){
                updateTime.setAccessible(true);
                updateTime.set(arg,LocalDateTime.now());
            }
        }
        Object proceed = pjp.proceed(args);
        return proceed;
    }
}
